// pages/address/select.js
import { getUserAddrs, deleteUserAddr, setDefaultAddr } from '../../utils/apis'
import { confirm, getPrevPage } from '../../utils/util'
const app = getApp()
Page({
    data: {},
    onLoad: function(options) {
        // 页面初始化 options为页面跳转所带来的参数
        this.cb = options.callback || 'callback'
        // this.setData({
        //   selectedId: options.id
        // })
        this.loadData()
    },
    onReady: function() {
        // 页面渲染完成
    },
    onShow: function() {
        // 页面显示
    },
    onHide: function() {
        // 页面隐藏
    },
    onUnload: function() {
        // 页面关闭
    },
    onPullDownRefresh() {
        this.loadData(function() {
            wx.stopPullDownRefresh()
        })
    },
    loadData(cb) {
        var that = this
        var { loading } = this.data
        if (loading) {
            return
        }
        this.setData({
            loading: true
        })
        wx.showNavigationBarLoading()
        app.getLoginInfo(loginInfo => {
            if (!loginInfo) {
                return alert('用户未登录')
            } else {
                getUserAddrs()
                    .then(result => {
                        that.setData({
                            list: result,
                            loading: false
                        })
                        wx.hideNavigationBarLoading()
                        cb && cb()
                    })
                    .catch(err => {
                        that.setData({
                            loading: false
                        })
                        wx.hideNavigationBarLoading()
                        cb && cb()
                    })
            }
        })
    },
    callback() {
        this.loadData()
    },
    onItemTap(e) {
        var that = this
        var type
        var id = e.currentTarget.id
        if (e.currentTarget.dataset) {
            type = e.currentTarget.dataset.type
        }
        if (type == 1) {
            wx.navigateBack()
            return
        } else {
            setDefaultAddr({ id, type: 1 })
                .then(data => {
                    that.setData({
                        loading: false
                    })
                    wx.hideNavigationBarLoading()
                    wx.navigateBack()
                })
                .catch(err => {
                    that.setData({
                        loading: false
                    })
                    wx.hideNavigationBarLoading()
                })
        }
    }
})